#include "adc.h"

void ADC_GPIO_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
}

void ADC_Configuration(void)
{
	ADC_InitTypeDef ADC_InitStructure;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
	
	RCC_ADCCLKConfig(RCC_ADCCLK_PCLK_Div4);
	
	ADC_DeInit(ADC1);
	
	ADC_StructInit(&ADC_InitStructure);
	
	ADC_InitStructure.ADC_ContinuousConvMode = 	ENABLE;
	ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
	ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
	ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
	ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
	ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC4 ;
	ADC_Init(ADC1,&ADC_InitStructure);
	
	ADC_ChannelConfig(ADC1,ADC_Channel_0,ADC_SampleTime_55_5Cycles);
	
	ADC_GetCalibrationFactor(ADC1);
	
	ADC_Cmd(ADC1,ENABLE);
	
	while(!ADC_GetFlagStatus(ADC1,ADC_FLAG_ADEN));
	ADC_StartOfConversion(ADC1);
}
uint32_t ResultVolt = 0;
uint32_t ADC_Check(void)
{
	uint32_t CurrResultVolt;
	//ADC_StartOfConversion(ADC1);
	for(int i = 0; i <8; i ++)
	{
		while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
		CurrResultVolt = ADC_GetConversionValue(ADC1);
		ResultVolt += CurrResultVolt;
	}
	ResultVolt = ResultVolt >> 3;
	ResultVolt =(ResultVolt*3300) >>12;
	
	return ResultVolt;
}

